package org.pblue.appengine.data.caching;

import java.util.Collections;
import java.util.logging.Logger;

import net.sf.jsr107cache.CacheException;
import net.sf.jsr107cache.CacheFactory;
import net.sf.jsr107cache.CacheManager;

public final class Cache {
  
  private static net.sf.jsr107cache.Cache cache;
  
  private static final Logger log = Logger.getLogger(Cache.class.getName());
  
  public static net.sf.jsr107cache.Cache cache() {
    if (cache == null) {
      try {
        CacheFactory cacheFactory = CacheManager.getInstance().getCacheFactory();
        cache = cacheFactory.createCache(Collections.emptyMap());
      } catch (CacheException e) {
        log.severe(e.getMessage());
      }
    }
    return cache;
  }
  
  public static Cacheable get(Object key) {
    Cacheable item = (Cacheable) cache().get(key);
    return item;
  }
  
  public static void add(Cacheable item) {
    cache().put(item.getCacheKey(), item);
  }
  
  public static void remove(Cacheable item) {
    remove(item.getCacheKey());
  }
  
  public static void remove(Object cacheKey) {
    Cacheable item = (Cacheable) cache().get(cacheKey);
    if (item != null) {
      cache().remove(cacheKey);

      for (Object key : item.getDependencies()) {
        Cacheable dependency = get(key);
        if (dependency != null) {
          remove(dependency);
        }
      }
    }
  }

}
